package org.scratchcrew.web.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.scratchcrew.services.security.SecurityContext;
import org.scratchcrew.services.security.SecurityContextHolder;
import org.scratchcrew.web.vo.UserInfo;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Filters requests
 * 
 */
public class SecurityFilter extends OncePerRequestFilter {

	private static final String DEFAULT_USER_SESSION_ATTRIBUTE_NAME = "user";
	private String userSessionAttributeName = DEFAULT_USER_SESSION_ATTRIBUTE_NAME;

	public void setUserSessionAttributeName(String userSessionAttributeName) {
		this.userSessionAttributeName = userSessionAttributeName;
	}

	protected String getUserSessionAttributeName() {
		return userSessionAttributeName;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String userName = null;
		if (session != null) {
			UserInfo userInfo = (UserInfo) session
					.getAttribute(getUserSessionAttributeName());
			if (userInfo != null) {
				userName = userInfo.getUserName();
			}
		}
		SecurityContext securityContext = null;
		if (userName != null) {
			logger.debug(String.format("Security context for user '%s' will be created", userName));
			securityContext = new SecurityContext(userName);
		} else {
			logger.debug("No userName found."
					+ " Current security context will be set to null.");
		}
		try {
			SecurityContextHolder.setSecurityContext(securityContext);
			filterChain.doFilter(request, response);
		} finally {
			SecurityContextHolder.cleanUpSecurityContext();
		}
	}

}
